<template>
  <div id="client">
    <p style="margin-left: 20px">
      <span class="demonstration" style="margin-left: 20px">日期：</span>
      <el-date-picker
        style="width: 160px"
        v-model="youxiaoqi"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始"
        end-placeholder="结束"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd hh:mm:ss              "
      >
      </el-date-picker>
      &nbsp;&nbsp;&nbsp; 单据编号：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="单据编号"
        v-model="initnum"
        clearable
      >
      </el-input>
      &nbsp;&nbsp;&nbsp; 客户编号：<el-input
        style="width: 180px; margin-left: 10px; margin-right: 20px"
        placeholder="请输入客户编号"
        v-model="customernum"
        clearable
      ></el-input>
      <el-button
        style="margin-left: -20px; margin-right: 10px"
        @click="dialogFormVisible3 = true"
        >...</el-button
      ><el-button type="primary" @click="goSelect()">查询</el-button>
      <el-divider></el-divider>

      <span
        style="
          display: inline-block;
          float: right;
          margin-right: 60px;
          margin-bottom: 20px;
        "
      >
        <el-button type="primary" @click="add()">发票登记</el-button>
        <el-button @click="goto('InvoicingList')">开票记录</el-button>
      </span>
    </p>
    <el-dialog top="20px" title="选择客户" :visible.sync="dialogFormVisible3">
      <ClientChoose
        ref="customerCode"
        :dialogFormVisible3="dialogFormVisible3"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="yesCustomer">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
      height="300px"
      :data="invoices"
      border
      style="width: 100%; font-size: 13px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="initTime" label="单据日期" width="150">
      </el-table-column>
      <el-table-column prop="initnum" label="单据编号" width="120">
      </el-table-column>
      <el-table-column prop="customernum" label="客户编号" width="120">
      </el-table-column>
      <el-table-column prop="totalprice" label="金额（元）" width="120">
      </el-table-column>
      <el-table-column prop="saler" label="销售人员编号" width="120">
      </el-table-column>
      <el-table-column prop="getMoney" label="已收款" width="120">
      </el-table-column>
      <el-table-column prop="piaomoney" label="已开票金额（元）" width="120">
      </el-table-column>
      <el-table-column prop="nopiaomoney" label="未开票金额（元）" width="120">
      </el-table-column>
      <el-table-column
        prop="nowpiaoMoney"
        label="本次开票金额（元）"
        width="120"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.nowpiaoMoney"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <el-divider></el-divider>
    <p style="margin-top: 10px; margin-bottom: 10px">
      开票日期：
      <el-date-picker
        v-model="createTime"
        type="datetime"
        placeholder="选择日期时间"
        value-format="yyyy-MM-dd HH:mm:ss"
      >
      </el-date-picker
      >&nbsp;&nbsp;&nbsp; 发票号：<el-input
        style="width: 200px; margin-left: 10px; margin-right: 20px"
        v-model="inum"
        clearable
      >
      </el-input>
      发票金额（元）：<el-input
        style="width: 200px; margin-left: 10px; margin-right: 20px"
        v-model="totalprice"
        clearable
      >
      </el-input>
    </p>
    <p style="">
      发票抬头：<el-input
        style="width: 200px; margin-left: 10px; margin-right: 20px"
        v-model="title"
        clearable
      >
      </el-input>
      开票备注：<el-input
        style="width: 200px; margin-left: 10px; margin-right: 20px"
        v-model="remark"
        clearable
      >
      </el-input>
    </p>
  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";
import ClientChoose from "../public_com/ClientChoose.vue";
export default {
  name: "Invoicing",
  components: {
    GoodsChoose,
    ClientChoose,
  },
  data() {
    return {
      youxiaoqi: "",
      totalprice: "",
      inum: "",
      remark: "",
      title: "",
      createTime: "",
      invoices: [],
      clientName: "",
      dialogFormVisible3: false,
      customernum: "",
      initnum: "",
      salesOrder: "",
      multipleSelection: "",
    };
  },
  computed: {
    totalList() {
      return {};
    },
  },
  created() {
    this.getInvoiceDetail();
  },
  methods: {
    validateData() {
      let errors = [];

      // 验证开票日期
      if (!this.createTime) {
        errors.push("开票日期不能为空。");
      }

      // 验证发票号
      if (!this.inum) {
        errors.push("发票号不能为空。");
      }

      // 验证发票金额
      if (!this.totalprice) {
        errors.push("发票金额不能为空。");
      } else if (isNaN(this.totalprice)) {
        errors.push("发票金额必须是数字。");
      } else if (!/^\d+(\.\d{1,2})?$/.test(this.totalprice)) {
        errors.push("发票金额应保留两位小数。");
      }

      // 验证发票抬头
      if (!this.title) {
        errors.push("发票抬头不能为空。");
      }

      // 验证开票备注
      if (!this.remark) {
        errors.push("开票备注不能为空。");
      }

      // 验证 invoices 数组中的每一项
      this.invoices.forEach((invoice, index) => {
        if (!invoice.nowpiaoMoney) {
          errors.push(`第 ${index + 1} 行：本次开票金额不能为空。`);
        } else if (isNaN(invoice.nowpiaoMoney)) {
          errors.push(`第 ${index + 1} 行：本次开票金额必须是数字。`);
        } else if (!/^\d+(\.\d{1,2})?$/.test(invoice.nowpiaoMoney)) {
          errors.push(`第 ${index + 1} 行：本次开票金额应保留两位小数。`);
        }
      });

      if (errors.length > 0) {
        alert(errors.join("\n"));
        return false;
      }

      return true;
    },
    goSelect() {
      this.getInvoiceDetail();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    add() {
      if (!this.validateData()) {
        return;
      }
      var invoices = [];
      this.multipleSelection.forEach((item) => {
        item.inum = this.inum;
        item.remark = this.remark;
        item.title = this.title;
        item.createTime = this.createTime;
        invoices.push(item);
      });
      console.log(invoices);
      var dataFormat = new FormData();
      dataFormat = {
        invoices: JSON.stringify(invoices),
      };
      console.log("dataFormat", dataFormat);
      this.axios
        .post("/erp/sale/invoice/add", {
          ...dataFormat,
        })
        .then((rs) => {
          if (rs.data.result) {
            alert("开票成功！");
            this.goto("InvoicingList");
            return;
          }
          alert("开票失败！");
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    getInvoiceDetail() {
      var documentNum = this.initnum;
      var startTime = this.youxiaoqi[0];
      var endTime = this.youxiaoqi[1];
      var customerNum = this.customernum;
      this.axios({
        url: "/erp/sale/invoice/getDetails",
        params: {
          documentNum,
          startTime,
          endTime,
          customerNum,
        },
      })
        .then((rs) => {
          console.log("details", rs.data.list);
          this.invoices = rs.data.list;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    yesCustomer() {
      this.dialogFormVisible3 = false;
      this.customerNum = this.$refs.customerCode.clientCode;
      this.clientName = this.$refs.customerCode.clientName;
    },
    goto(to) {
      if (this.$route.path !== "/" + to) {
        this.$router.push(to);
      }
    },
  },
};
</script>

<style scoped>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

tr {
  border: 1px solid black;
}
</style>